package com.cdqidi.core.weixinmanager.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.core.weixinmanager.domain.OrgWxConfigDTO;
import com.cdqidi.core.weixinmanager.mapper.OrgWxConfigMapper;
import com.cdqidi.core.weixinmanager.model.OrgWxConfig;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.jfinal.springboot.weixin.config.WeiXinConfiguration;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.WxaConfigKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrgWxConfigService extends BaseService<OrgWxConfigMapper, OrgWxConfig> {

    private static final String PREFIX_ID = "sys_wx_org_wx_config_appId_{0}";

    private final RedisTemplateUtil<OrgWxConfig> redisTemplateUtil;
    private final WeiXinConfiguration weiXinConfiguration;
    @Resource
    private HttpServletResponse response;

    public List<OrgWxConfig> getAll() {
        return super.list();
    }

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public OrgWxConfigDTO save(OrgWxConfigDTO dto) {
        final OrgWxConfig model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public OrgWxConfigDTO update(OrgWxConfigDTO dto) {
        final OrgWxConfig historyModel = Optional.ofNullable(getById(dto.getAppId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final OrgWxConfig model = dtoToModel(dto);
        try {
            if (!super.updateById(model)) {
                throw new ApiException("更新失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
        return getByIdDto(dto.getAppId());
    }

    /**
     * 删除，单个
     *
     * @param appId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String appId) {
        final OrgWxConfig model = Optional.ofNullable(getById(appId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(appId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(OrgWxConfigDTO dto) {
        final QueryWrapper<OrgWxConfig> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param appId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String appId) {
        boolean exists = false;
        if (StringUtils.hasLength(appId)) {
            final OrgWxConfig model = getById(appId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param appId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public OrgWxConfig getById(String appId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, appId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(appId), OrgWxConfig.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param appId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public OrgWxConfigDTO getByIdDto(String appId) {
        return Optional.ofNullable(getById(appId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public OrgWxConfig getOne(OrgWxConfigDTO dto) {
        final QueryWrapper<OrgWxConfig> queryWrapper = createQueryWrapper(dto);
        OrgWxConfig model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public OrgWxConfigDTO getOneDto(OrgWxConfigDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<OrgWxConfig> getList(OrgWxConfigDTO dto) {
        final QueryWrapper<OrgWxConfig> queryWrapper = createQueryWrapper(dto);
        final List<OrgWxConfig> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<OrgWxConfigDTO> getListDto(OrgWxConfigDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OrgWxConfigDTO> page(Page<OrgWxConfig> page, OrgWxConfigDTO dto) {
        final QueryWrapper<OrgWxConfig> queryWrapper = createQueryWrapper(dto, "org.");
        final IPage<OrgWxConfigDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(OrgWxConfigDTO query) {
        final ExportPage<OrgWxConfig, OrgWxConfigDTO> exportPage = new ExportPage<>();
        try {
            final List<OrgWxConfigDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, OrgWxConfigDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }

    private void clearCache(String id) {
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id));
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(OrgWxConfig model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getAppId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public OrgWxConfigDTO modelToDto(OrgWxConfig model) {
        if (null == model) {
            return null;
        }
        final OrgWxConfigDTO dto = new OrgWxConfigDTO();
        dto.setAppId(model.getAppId());
        dto.setAppName(model.getAppName());
        dto.setToken(model.getToken());
        dto.setAppSecret(model.getAppSecret());
        dto.setEncryptMessage(model.getEncryptMessage());
        dto.setEncodeAesKey(model.getEncodeAesKey());
        dto.setRemark(model.getRemark());
        dto.setSecurity(model.getSecurity());
        dto.setSecurityFileName(model.getSecurityFileName());
        dto.setMchId(model.getMchId());
        dto.setApiKey(model.getApiKey());
        dto.setCertificate(model.getCertificate());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setWxAccountType(model.getWxAccountType());
        dto.setOrgId(model.getOrgId());
        dto.setOperator(model.getOperator());
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public OrgWxConfig dtoToModel(OrgWxConfigDTO dto) {
        if (null == dto) {
            return null;
        }
        final OrgWxConfig model = new OrgWxConfig();
        model.setAppId(dto.getAppId());
        model.setAppName(dto.getAppName());
        model.setToken(dto.getToken());
        model.setAppSecret(dto.getAppSecret());
        model.setEncryptMessage(dto.getEncryptMessage());
        model.setEncodeAesKey(dto.getEncodeAesKey());
        model.setRemark(dto.getRemark());
        model.setSecurity(dto.getSecurity());
        model.setSecurityFileName(dto.getSecurityFileName());
        model.setMchId(dto.getMchId());
        model.setApiKey(dto.getApiKey());
        model.setCertificate(dto.getCertificate());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setWxAccountType(dto.getWxAccountType());
        model.setOrgId(dto.getOrgId());
        model.setOperator(dto.getOperator());
        return model;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<OrgWxConfigDTO> modelToDtoList(List<OrgWxConfig> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<OrgWxConfig> dtoToModelList(List<OrgWxConfigDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<OrgWxConfig> createQueryWrapper(OrgWxConfigDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<OrgWxConfig> createQueryWrapper(OrgWxConfigDTO dto, String tableAlias) {
        final QueryWrapper<OrgWxConfig> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getAppName())) {
                queryWrapper.eq(tableAlias + "app_name", dto.getAppName());
            }
            if (StringUtils.hasLength(dto.getToken())) {
                queryWrapper.eq(tableAlias + "token", dto.getToken());
            }
            if (StringUtils.hasLength(dto.getAppSecret())) {
                queryWrapper.eq(tableAlias + "app_secret", dto.getAppSecret());
            }
            if (StringUtils.hasLength(dto.getEncodeAesKey())) {
                queryWrapper.eq(tableAlias + "encode_aes_key", dto.getEncodeAesKey());
            }
            if (StringUtils.hasLength(dto.getRemark())) {
                queryWrapper.eq(tableAlias + "remark", dto.getRemark());
            }
            if (StringUtils.hasLength(dto.getSecurityFileName())) {
                queryWrapper.eq(tableAlias + "security_file_name", dto.getSecurityFileName());
            }
            if (StringUtils.hasLength(dto.getMchId())) {
                queryWrapper.eq(tableAlias + "mch_id", dto.getMchId());
            }
            if (StringUtils.hasLength(dto.getApiKey())) {
                queryWrapper.eq(tableAlias + "api_key", dto.getApiKey());
            }
            if (StringUtils.hasLength(dto.getWxAccountType())) {
                queryWrapper.eq(tableAlias + "wx_account_type", dto.getWxAccountType());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getOperator())) {
                queryWrapper.eq(tableAlias + "operator", dto.getOperator());
            }
        }
        return queryWrapper;
    }

    @Transactional(readOnly = true)
    public OrgWxConfig getWxConfig() {
        final String appId = ApiConfigKit.getAppId();
        return Optional.ofNullable(getById(appId)).orElseThrow(() -> new ApiException("请在数据库中配置微信公众平台注册信息,appId: " + appId));
    }

    /**
     * 重新加载配置信息到jfinal-weixin中
     *
     * @param dto 前端对象 type 1添加或者更新 2删除
     * @return 成功
     */
    public ApiResultWrapper<Object> onLoadOrgWxConfig(OrgWxConfigDTO dto) {
        Integer type = dto.getType();
        OrgWxConfig model = dtoToModel(dto);
        //小程序
        if (model.getWxAccountType().equals(ConstantDto.WX_ACCOUNT_TYPE_APP)) {
            final WxaConfig wxaConfig = convertToWxaConfig(model);
            if (type == 1) {
                //添加或者更新
                WxaConfigKit.putWxaConfig(wxaConfig);
            } else {
                WxaConfigKit.removeWxaConfig(wxaConfig);
            }
        } else {
            //公众号
            final ApiConfig apiConfig = convertToApiConfig(model);
            if (type == 1) {
                //添加或者更新
                ApiConfigKit.putApiConfig(apiConfig);
            } else {
                ApiConfigKit.removeApiConfig(apiConfig);
            }
        }
        String key = weiXinConfiguration.getAccessTokenCacheName() + model.getAppId();
        log.info("清理缓存accessToken，key: " + key);
        ApiConfigKit.getAccessTokenCache().remove(key);
        clearCache(model.getAppId());
        model.freeData();
        return ApiResult.success();
    }

    public ApiConfig convertToApiConfig(OrgWxConfig model) {
        ApiConfig apiConfig = new ApiConfig();
        apiConfig.setAppId(model.getAppId());
        apiConfig.setAppSecret(model.getAppSecret());
        apiConfig.setEncodingAesKey(model.getEncodeAesKey());
        apiConfig.setToken(model.getToken());
        apiConfig.setEncryptMessage(model.getEncryptMessage());
        return apiConfig;
    }

    public WxaConfig convertToWxaConfig(OrgWxConfig model) {
        WxaConfig wxaConfig = new WxaConfig();
        wxaConfig.setAppId(model.getAppId());
        wxaConfig.setAppSecret(model.getAppSecret());
        wxaConfig.setEncodingAesKey(model.getEncodeAesKey());
        wxaConfig.setToken(model.getToken());
        wxaConfig.setMessageEncrypt(model.getEncryptMessage());
        return wxaConfig;
    }

    @Transactional(readOnly = true)
    public String idToDisplay(String appId) {
        String appName = "";
        if (StringUtils.hasLength(appId)) {
            final OrgWxConfig orgWxConfig = getById(appId);
            appName = (null == orgWxConfig ? "" : orgWxConfig.getAppName());
        }
        return appName;
    }
}